package org.xtense.data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.xtense.exception.XtenseException;
import org.xtense.log.iLog;


public class DBManager {
	private Connection conn;
	private DBConfig config;
	
	/**
	 * Constructor
	 */
	public DBManager() {
		this(new DBConfigFromFile());
	}
	
	public DBManager(DBConfig config) {
		this.config = config;
		validateConnection();
	}
	
	@SuppressWarnings("finally")
	public boolean validateConnection() {
		boolean canConn = true;
		if(conn == null) {
			try {
				iLog.info("Finding the driver...");
				Class.forName(config.getDriver());
				iLog.info("initialize a connection");
				conn = DriverManager.getConnection(config.getUrl(), config
						.getUsername(), config.getPassword());
			} catch (ClassNotFoundException e) {
				canConn = false;
				try {
					throw new XtenseException(XtenseException.NoDriverError);
				} catch (XtenseException e1) {
					iLog.warn(e1);
				}
			}catch (SQLException e) {
				canConn = false;
				try {
					throw new XtenseException(XtenseException.ConnectionFailure);
				} catch (XtenseException e1) {
					iLog.warn(e);
				}
			} finally {
				return canConn;
			}
		}
		return canConn;
	}
	
	public ResultSet executeSqlQuery( String sql ) {
		ResultSet result = null;
		if( validateConnection() ) {
			Statement statement;
			try {
				statement = conn.createStatement();
				result = statement.executeQuery(sql);
			} catch (SQLException e) {
				iLog.error(e);
			}
		} else {
			//throws exception
		}
		return result;
		
	}
	
	public int executeSqlUpdate(String sql) {
		int result=0;
		if(validateConnection()) {
			Statement statement;
			try {
				statement=conn.createStatement();
				result=statement.executeUpdate(sql);
			} catch (SQLException e) {
				iLog.error(e);
			}
			
		} else {
			//throws exception
		}
		return result;
	}
	
}
